package com.sinotrans.sql;
import java.net.InetSocketAddress; 
import java.nio.channels.AsynchronousChannelGroup; 
import java.nio.channels.AsynchronousServerSocketChannel; 
import java.nio.channels.AsynchronousSocketChannel; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future;

import com.sinotrans.sql.handler.AcceptHandler; 
public class Startup implements Runnable{
	private AsynchronousChannelGroup asyncChannelGroup;  
    private AsynchronousServerSocketChannel listener; 
	
    public Startup(int port) throws Exception { 
        //创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(20); 
        //异步通道管理器
        asyncChannelGroup = AsynchronousChannelGroup.withThreadPool(executor); 
        //创建 用在服务端的异步Socket.以下简称服务器socket。
        //异步通道管理器，会把服务端所用到的相关参数
        listener = AsynchronousServerSocketChannel.open(asyncChannelGroup).
                bind(new InetSocketAddress(port)); 
    } 
    
    

	@Override
	public void run() {
		 try { 
                //为服务端socket指定接收操作对象.accept原型是：
	            //accept(A attachment, CompletionHandler<AsynchronousSocketChannel,
	            // ? super A> handler)
	            //也就是这里的CompletionHandler的A型参数是实际调用accept方法的第一个参数
	            //即是listener。另一个参数V，就是原型中的客户端socket
	            listener.accept(listener, new AcceptHandler());  
	            Thread.sleep(400000); 
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } finally { 
	            System.out.println("finished server");
	        }
		
	}
	public static void main(String[] args) throws Exception {
		Startup server = new Startup(9008); 
        new Thread(server).start(); 

	}

}
